package org.hshk.message.mq;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import org.hshk.message.service.CpMsgMemberSignService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.annotation.WebListener;

/**
 * Created With IntelliJ IDEA
 * User: WangYong
 * Date: 2017/2/25 0024
 * Time: 09:38
 * ProjectName: msgCenterAPI
 * 短信平台消息消费者
 */
@WebListener
public class MQConsumer implements MessageListener {
    //日志记录类
    private static final Logger log = LoggerFactory.getLogger(MQConsumer.class);
    @Autowired
    private CpMsgMemberSignService cpMsgMemberSignService;

    /**
     * 2017年2月26日 00:49:16
     *
     * @param message
     * @param context
     * @return
     */
    @Override
    public Action consume(Message message, ConsumeContext context) {
        try {
            String msgBody = new String(message.getBody(), "UTF-8");
            JSONObject json = JSONObject.parseObject(msgBody);
            //参数获取
            int brandId = json.getInteger("brandId");
            String mobile = json.getString("mobile");
            String templateCode = json.getString("templateCode");
            String parameters = json.getString("parameters");

            String sourceString = parameters.replaceAll("\"", "");
            //日志判定参数为1个时与多个时处理方式是不相同的
            if (sourceString.split("\\,").length == 1) {
                cpMsgMemberSignService.sendMessage(brandId, mobile, templateCode, new String[]{sourceString});
            } else {
                cpMsgMemberSignService.sendMessage(brandId, mobile, templateCode, parameters.split("\\,"));
            }
            //生成日志
            log.info(" ALiMQCoducer 消费数据成功 [ brandId=" + brandId + ", messageKey=" + message.getKey()
                    + ", messageId=" + message.getMsgID());
        } catch (Exception ex) {
            ex.printStackTrace();
            return Action.ReconsumeLater;
        }
        return Action.CommitMessage;
    }
}